#include "mainwindow.h"
#include "ui_mainwindow.h"

#define BUFFER_SIZE 4096      //串口一帧数据
#define SAMPLE_RATE 1024*10  //采样率
#define FFT_SIZE    4096     //fft点数

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    serialport = new QSerialPort(this);

    timer = new QTimer(this);//定时器0
    timer1 = new QTimer(this);//定时器1
    timer->start(1000);

    connect(timer,SIGNAL(timeout()),this,SLOT(timer_1000ms()));//1000ms中断
    connect(serialport,SIGNAL(readyRead()),this,
            SLOT(comRead()));
    connect(timer1,SIGNAL(timeout()),this,SLOT(timer_serial_rx()));//串口延时中断
    scanSerialPort();

    //fft
    fft* my_fft = new fft();


    //绘图部分

    waveData = QSharedPointer<QCPGraphDataContainer>(new QCPGraphDataContainer);
    fftData = QSharedPointer<QCPGraphDataContainer>(new QCPGraphDataContainer);
    /* 绘图初始化 */
    ui->plot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);//允许用户拖动图像以及调整坐标轴范围
    ui->plot->legend->setVisible(true);
    QFont legendFont = font();//字体
    legendFont.setPointSize(16);//字号
    ui->plot->legend->setFont(legendFont);
    ui->plot->legend->setSelectedFont(legendFont);
    ui->plot->legend->setSelectableParts(QCPLegend::spItems);

    ui->plot->yAxis->setLabel("Volt(V)");//设置y标题
    ui->plot->xAxis->setLabel("Time");//设置x标题
    ui->plot->axisRect()->setBackground(QBrush(Qt::black));   //设置背景颜色
    ui->plot->addGraph();//添加曲线
    ui->plot->graph(0)->setPen(QPen(Qt::red));//曲线颜色 红色
    ui->plot->graph(0)->setData(waveData);//添加绘制的点
    ui->plot->graph(0)->setName("ADC");//曲线名称

    // 设置x坐标轴显示范围，使其自适应缩放x轴，x轴最大显示1000个点


}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::scanSerialPort()
{
    //查询可用的串口信息
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        {
            //添加串口到下拉菜单
            ui->setPortname->addItem(info.portName());
        }
        qDebug()<<"已发现串口："<<ui->setPortname->currentText();
    }
}

void MainWindow::reflash_com()
{

    ui->setPortname->clear();//清除选择串口下拉栏添加的所有项目
    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts())
    {
        {
            ui->setPortname->addItem(info.portName());
        }
    }
    ui->setPortname->setCurrentIndex(choose_index);
    qDebug()<<"choose_index:"<<choose_index;
}

void MainWindow::serialPortInit()
{
    //设置串口名称
    serialport->setPortName(ui->setPortname->currentText());
    qDebug()<<"串口名称:"<<serialport->portName();

     if (!serialport->open(QIODevice::ReadWrite))
    {
        qDebug()<<"错误，串口无法打开，可能被占用！";
        QMessageBox::about(this,"错误","串口无法打开，可能被占用！");
        serialport->close();
        return ;
    }

    //波特率
    serialport->setBaudRate(ui->setBaudRate->currentText().toInt());
    qDebug()<<"波特率:"<<ui->setBaudRate->currentText().toInt();
                             //停止位
                             switch (ui->setStopbits->currentText().toInt())
    {
    case 1 :  serialport->setStopBits(QSerialPort::OneStop); break;
    case 2 :  serialport->setStopBits(QSerialPort::TwoStop); break;
    default: break;
    }
    qDebug()<<"停止位:"<<serialport->stopBits();
                             //数据位
                             switch (ui->setDatabits->currentText().toInt())
    {
    case 5 :  serialport->setDataBits(QSerialPort::Data5); break;
    case 6 :  serialport->setDataBits(QSerialPort::Data6); break;
    case 7 :  serialport->setDataBits(QSerialPort::Data7); break;
    case 8 :  serialport->setDataBits(QSerialPort::Data8); break;
    default: break;
    }
    //奇偶位
    switch (ui->setParity->currentIndex())
    {
    case 0 :  serialport->setParity(QSerialPort::NoParity); break;
    case 1 :  serialport->setParity(QSerialPort::OddParity); break;
    case 2 :  serialport->setParity(QSerialPort::EvenParity); break;
    default: break;
    }
    qDebug()<<"奇偶位:"<<serialport->parity();

                                     serialport->setFlowControl(QSerialPort::NoFlowControl) ;


}


void MainWindow::on_pbStartDisplay_clicked()//开始显示
{
     if (btn_wave_on == 0)
     {


        ui->pbStartDisplay->setText("停止显示");
     }

     if (btn_wave_on == 1)
     {

        ui->pbStartDisplay->setText("开始显示");
     }
     btn_wave_on = !btn_wave_on;
}




void MainWindow::on_pbclearwave_clicked()//清空波形
{
     btn_clearwave_on=1;


}


void MainWindow::on_pbsavewave_clicked()//保存波形
{

}


void MainWindow::on_lineEdit_buffersize_editingFinished()//波形显示缓冲区大小
{
  wave_size=ui->lineEdit_buffersize->text().toInt();
}

void MainWindow::serialPortWrite()
{
   QByteArray buff;
   QString strTXdata;
   QByteArray hexdata;

     //判断是否非空
     if(!ui->textEdit_tx->toPlainText().isEmpty())
         {
        if(ui->tx_checkBox->isChecked()==false)//字符模式
              {
                buff = ui->textEdit_tx->toPlainText().toLocal8Bit();//可以写中文
                serialport->write(buff);
              }
             else//16进制码模式
              {
                //strTXdata = ui->textEdit_tx->toPlainText().toAscii();
                //stringToHex(strTXdata,hexdata);
                serialport->write(hexdata);
              }
          }
}

void MainWindow::on_pbSent_clicked()
{
            serialPortWrite();
}


void MainWindow::on_pbClearsent_clicked()
{
    ui->textEdit_tx->clear();
}


void MainWindow::on_openSerialports_clicked()
{
     if (btn_serial_on == 0)
       {

        ui->setPortname->setEnabled(false);
        ui->setBaudRate->setEnabled(false);
        ui->setDatabits->setEnabled(false);
        ui->setStopbits->setEnabled(false);
        ui->setParity->setEnabled(false);
        ui->openSerialports->setText("关闭串口");
        qDebug()<<"打开串口:";
        serialPortInit();
       }

     if (btn_serial_on == 1)
       {

        serialport->close();
        ui->setPortname->setEnabled(true);
        ui->setBaudRate->setEnabled(true);
        ui->setDatabits->setEnabled(true);
        ui->setStopbits->setEnabled(true);
        ui->setParity->setEnabled(true);
        ui->openSerialports->setText("打开串口");
       }
     btn_serial_on = !btn_serial_on;
}


void MainWindow::on_Clear_rx_clicked()
{
    ui->textEdit_rx->clear();
}


void MainWindow::timer_1000ms()
{
    QTime time = QTime::currentTime();
    QDate date = QDate::currentDate();
    ui->label_date_time->setText(date.toString("yyyy-MM-dd") +" "+ time.toString("hh:mm:ss"));
    ui->textEdit_rx->setFontPointSize(ui->setFontPointsize->currentText().toInt());

}

void MainWindow::comRead()//接收到串口信号，开启延时，准备接收数据
{

    timer1->start(100);//设置合适时间延时
    buffer1.append(serialport->readAll());

    ui->textEdit_rx->setText(buffer1.left(128));
}

int getMax(QByteArray data)
{
    int len =data.count();
    int Max=0;
    for(int i=0;i<len;i++)
    {
        Max= (unsigned char)data.at(i)>Max?(unsigned char)data.at(i):Max;
    }
    return Max;
}
double getMax(double *data)
{
    int len =sizeof(data);
    int Max=0;
    for(int i=0;i<len;i++)
    {
        Max= (unsigned char)data[i]>Max?(unsigned char)data[i]:Max;
    }
    return Max;
}

int t=0;
QVector<Complex> in_(FFT_SIZE);
QVector<Complex> out_(FFT_SIZE);
void MainWindow::timer_serial_rx()
{

    timer1->stop();//关闭定时器
    QByteArray data = buffer1;//读取缓冲区数据
    buffer1.clear();//清除缓冲区
    data = data.left(BUFFER_SIZE);//保留开始的4096个数据

     ui->label_rx_ok->setText("OK");

    int wave_sum[BUFFER_SIZE];
    int num_of_0=0;
    int num_of_iden=0;
    //对接收的数据进行处理并进行绘制
    if( btn_wave_on==1)
    {
        for(int i=0;i<BUFFER_SIZE/2;i++)
        {
            wave_sum[i]=(unsigned char )data.at(i+1)-(unsigned char )data.at(i);
            if(wave_sum[i]==0)num_of_0++;
             if(wave_sum[i]==wave_sum[(i-1)>=0?(i-1):0]&&wave_sum[i]!=0)num_of_iden++;
        }

       // ui->text_waveform->setText(QString::toLocal8Bit(num_of_0) );
        if(num_of_iden>0.3*BUFFER_SIZE/2)
        {
             ui->text_waveform->setText("三角波");
            // ui->lcd_f->display((data.count(0x80)/2)*(SAMPLE_RATE/BUFFER_SIZE));
        }
        else if(num_of_0>0.6*BUFFER_SIZE/2)ui->text_waveform->setText("方波");
        else
        {
             ui->text_waveform->setText("正弦波");
            // ui->lcd_f->display((data.count(0x80)/2)*(SAMPLE_RATE/BUFFER_SIZE));
        }

        for(int i=0;i<BUFFER_SIZE;i++)
        {

            unsigned char mag = data.at(i);

             waveData->add(QCPGraphData(t, (double)((double)(mag-127)/128.0f)*5));//将收到的数据放入waveData中
            t++;

        }
        if(btn_clearwave_on==1)
        {
            waveData->clear();
            t=0;
            btn_clearwave_on=0;


        }
      //  for(int i=0;i<FFT_SIZE;i++)
       // {
       //     in_[i].rl = (unsigned char)data.at(i)-127;//FFT入口数据
       // }
        if(btn_fft_on==0)//时域波形显示
        {
           //  my_fft->fft1(in_,in_.size(),out_);//fft计算
           // int j=0;
           // int max=0;
           // for(int i=0;i<FFT_SIZE/2;i++)
          //  {
         //       if(max<fabs(out_[i].rl))
          //      {
          //          max=fabs(out_[i].rl);
            //        j=i;
           //     }

           // }
          //  ui->lcdNumber->display((j*((double)SAMPLE_RATE/(double)FFT_SIZE)));

            ui->plot->xAxis->setRange((waveData->size()>wave_size)?(waveData->size()-wave_size):0, waveData->size());
            ui->plot->yAxis->setRange(-5,+5);
            ui->plot->replot(QCustomPlot::rpQueuedReplot);//重绘
        }
        else//频域波形显示
        {

            fftData->clear();
             my_fft->fft1(in_,in_.size(),out_);//fft计算
            int j=0;
            int max=0;
            for(int i=0;i<FFT_SIZE/2;i++)
            {
                if(max<fabs(out_[i].rl))
                {
                    max=fabs(out_[i].rl);
                    j=i;
                }

            }
            ui->lcdNumber->display((j*((double)SAMPLE_RATE/(double)FFT_SIZE)));
            for(int i=0;i<FFT_SIZE/2;i++)
             {
                 fftData->add(QCPGraphData(i*((double)SAMPLE_RATE/(double)FFT_SIZE), out_[i].rl));//载入曲线数据
             }
            ui->plot->rescaleAxes();
            ui->plot->replot(QCustomPlot::rpQueuedReplot);//重绘

        }


    }

}

void MainWindow::on_pbFFT_clicked()
{
    if (btn_fft_on == 0)
    {
        ui->plot->yAxis->setLabel("幅度");//设置y标题
        ui->plot->xAxis->setLabel("频率（Hz）");//设置x标题
        ui->plot->axisRect()->setBackground(QBrush(Qt::white));   //设置背景颜色
        ui->plot->clearGraphs();
        ui->plot->addGraph();//添加曲线
        ui->plot->graph(0)->setPen(QPen(Qt::blue));//曲线颜色 蓝色
        ui->plot->graph(0)->setData(fftData);//添加绘制的点
        ui->plot->graph(0)->setName("FFT");//曲线名称

         ui->pbFFT->setText("关闭FFT");
    }

    if (btn_fft_on == 1)
    {
         ui->plot->yAxis->setLabel("Volt(V)");//设置y标题
         ui->plot->xAxis->setLabel("Time");//设置x标题
         ui->plot->axisRect()->setBackground(QBrush(Qt::black));   //设置背景颜色
         ui->plot->clearGraphs();
        ui->plot->addGraph();//添加曲线
         ui->plot->graph(0)->setPen(QPen(Qt::red));//曲线颜色 红色
         ui->plot->graph(0)->setData(waveData);//添加绘制的点
         ui->plot->graph(0)->setName("ADC");//曲线名称
         ui->pbFFT->setText("FFT");
    }
    btn_fft_on = !btn_fft_on;



}


void MainWindow::on_setUnderbaudrate_activated(int index)
{
    ui->textEdit_tx->clear();
    switch(index)
    {
 //   case 0: ui->textEdit_tx->setText("A");break;
    case 0: ui->textEdit_tx->setText("A");break;
    case 1: ui->textEdit_tx->setText("B");break;
    case 2: ui->textEdit_tx->setText("C");break;
    case 3: ui->textEdit_tx->setText("P");break;
    }
}


void MainWindow::on_setWaveform_activated(int index)
{
    ui->textEdit_tx->clear();
    switch(index)
    {
    case 0: ui->textEdit_tx->setText("D");break;
    case 1: ui->textEdit_tx->setText("E");break;
    case 2: ui->textEdit_tx->setText("F");break;
    case 3: ui->textEdit_tx->setText("G");break;
    }
}




void MainWindow::on_setADCrate_activated(int index)
{
    ui->textEdit_tx->clear();
    switch(index)
    {
    case 0: ui->textEdit_tx->setText("H");break;
    case 1: ui->textEdit_tx->setText("I");break;
    case 2: ui->textEdit_tx->setText("J");break;
    case 3: ui->textEdit_tx->setText("K");break;
    }
}


void MainWindow::on_setDACrate_activated(int index)
{
    ui->textEdit_tx->clear();
    switch(index)
    {
    case 0: ui->textEdit_tx->setText("L");break;
    case 1: ui->textEdit_tx->setText("M");break;
    case 2: ui->textEdit_tx->setText("N");break;
    case 3: ui->textEdit_tx->setText("O");break;

    }
}


void MainWindow::on_setPortname_activated(int index)
{

   if(choose_index !=index) choose_index = index;

}


void MainWindow::on_flashport_clicked()
{
   if (btn_serial_on == 0)//判断串口处于未打开状态
   {
         reflash_com();
   }
}


